package com.xjrsoft.module.organization.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.toolkit.MPJWrappers;
import com.xjrsoft.common.annotation.XjrLog;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.model.result.R;
import com.xjrsoft.common.utils.RedisUtil;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.organization.dto.UpdateApprovalSpecialListDto;
import com.xjrsoft.module.organization.entity.*;
import com.xjrsoft.module.organization.service.IApprovalSpecialistService;
import com.xjrsoft.module.organization.service.IDepartmentApprovalUserService;
import com.xjrsoft.module.organization.vo.ApprovalSpecialistVo;
import com.xjrsoft.module.organization.vo.DepartmentApprovalUserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 审批专员表 前端控制器
 * </p>
 *
 * @author hnyyzy
 * @since 2024-03-07
 */
@RestController
@RequestMapping(GlobalConstant.ORGANIZATION_MODULE_PREFIX + "/approvalSpecialist")
@Api(value = GlobalConstant.ORGANIZATION_MODULE_PREFIX + "/approvalSpecialist", tags = "审批专员")
@AllArgsConstructor
public class ApprovalSpecialistController {

    private final IApprovalSpecialistService approvalSpecialistService;

    private final IDepartmentApprovalUserService departmentApprovalUserService;

    private final RedisUtil redisUtil;

    @GetMapping(value = "/list")
    @ApiOperation(value = "机构列表(不分页)")
    @XjrLog(value = "获取不分页机构列表")
    public R list() {
        List<ApprovalSpecialist> list = approvalSpecialistService.list(Wrappers.lambdaQuery(ApprovalSpecialist.class)
                .orderByAsc(ApprovalSpecialist::getSortCode)
                .select(ApprovalSpecialist.class, x -> VoToColumnUtil.fieldsToColumns(ApprovalSpecialistVo.class).contains(x.getProperty())));

        List<ApprovalSpecialistVo> departmentListVos = BeanUtil.copyToList(list, ApprovalSpecialistVo.class);
        return R.ok(departmentListVos);
    }

    @GetMapping(value = "/department-list")
    @ApiOperation(value = "根据部门id获取该部门的审批专员人员配置(需要把所有审批专员都返回)")
    public R departmentList(@RequestParam Long departmentId) {
        List<DepartmentApprovalUserVo> departmentApprovalUserVoList = new ArrayList<>();
        List<DepartmentApprovalUser> departmentApprovalUserList = departmentApprovalUserService.list(Wrappers.<DepartmentApprovalUser>lambdaQuery().eq(DepartmentApprovalUser::getDepartmentId, departmentId));
        List<ApprovalSpecialist> approvalSpecialists = approvalSpecialistService.list();
        if (approvalSpecialists.size() > 0){
            List<User> userList = redisUtil.get(GlobalConstant.USER_CACHE_KEY, new TypeReference<List<User>>() {
            });
            for (ApprovalSpecialist approvalSpecialist : approvalSpecialists) {
                DepartmentApprovalUserVo departmentApprovalUserVo = new DepartmentApprovalUserVo();
                departmentApprovalUserVo.setApprovalSpecialistId(approvalSpecialist.getId());
                departmentApprovalUserVo.setApprovalSpecialistName(approvalSpecialist.getName());
                departmentApprovalUserVo.setDepartmentId(departmentId);
                if (departmentApprovalUserList.size() > 0){
                    Optional<DepartmentApprovalUser> departmentApprovalUser = departmentApprovalUserList.stream().filter(x -> x.getApprovalSpecialistId().equals(approvalSpecialist.getId())).findFirst();
                    if (departmentApprovalUser.isPresent()){
                        departmentApprovalUserVo.setId(departmentApprovalUser.get().getId());
                        Long userId = departmentApprovalUser.get().getUserId();
                        departmentApprovalUserVo.setUserId(userId);
                        Optional<User> user = userList.stream().filter(x->x.getId().equals(userId)).findFirst();
                        if (user.isPresent()){
                            departmentApprovalUserVo.setUserName(user.get().getName());
                            departmentApprovalUserVo.setEmailCount(user.get().getEmail());
                            departmentApprovalUserVo.setPhoneNumber(user.get().getMobile());
                        }
                    }
                }
                departmentApprovalUserVoList.add(departmentApprovalUserVo);
            }
        }else {
            return R.error("还未进行审批专员配置");
        }

        return R.ok(departmentApprovalUserVoList);
    }

    @PutMapping
    @ApiOperation(value = "修改审批专员")
    @XjrLog(value = "修改审批专员")
    public R update(@Valid @RequestBody List<UpdateApprovalSpecialListDto> dto) {
        //先查询当前所有的审批专员信息
        List<ApprovalSpecialist> list = approvalSpecialistService.list();
        if (list.size() > 0){
            //原本所有的审批专员信息ids
            List<Long> oldIds = list.stream().map(ApprovalSpecialist::getId).collect(Collectors.toList());
            List<ApprovalSpecialist> approvalSpecialists = BeanUtil.copyToList(dto, ApprovalSpecialist.class);
            List<Long> newIds = new ArrayList<>();
            //修改或者新增
            Integer sortCode = 0;
            for (ApprovalSpecialist approvalSpecialist : approvalSpecialists) {
                approvalSpecialist.setSortCode(sortCode);
                sortCode = sortCode + 1;
                if (ObjectUtil.isNotEmpty(approvalSpecialist.getId())){ //修改
                    Optional<ApprovalSpecialist> first = list.stream().filter(x -> x.getName().equals(approvalSpecialist.getName()) && !x.getId().equals(approvalSpecialist.getId())).findFirst();
                    if (first.isPresent()) {
                        return R.error("【" + approvalSpecialist.getName() + "】该审批专员名称已存在！");
                    }
                    //将修改的id存到数组中
                    newIds.add(approvalSpecialist.getId());
                }else {//新增
                    //判断审批专员名称是否重复
                    Optional<ApprovalSpecialist> first = list.stream().filter(x -> x.getName().equals(approvalSpecialist.getName())).findFirst();
                    if (first.isPresent()) {
                        return R.error("【" + approvalSpecialist.getName() + "】该审批专员名称已存在！");
                    }
                }
            }
            //对数据做新增和编辑
            approvalSpecialistService.saveOrUpdateBatch(approvalSpecialists);
            //删除,获取老的审批专员的ids与新的ids的差集，就是需要删除的ids
            List<Long> subtractList = (List<Long>) CollectionUtil.subtract(oldIds, newIds);
            if (subtractList.size() > 0){
                List<DepartmentApprovalUser> departmentApprovalUserList = departmentApprovalUserService.list();
                if (departmentApprovalUserList.size() > 0){
                    List<DepartmentApprovalUser> collect = departmentApprovalUserList.stream().filter(x -> subtractList.contains(x.getApprovalSpecialistId())).collect(Collectors.toList());
                    if (collect.size() > 0){
                        //先删除审批专员下的所有人员
                        departmentApprovalUserService.removeBatchByIds(collect);
                    }
                }
                //再删除审批专员
                approvalSpecialistService.removeByIds(subtractList);
            }
        }else {//新增
            List<ApprovalSpecialist> approvalSpecialists = BeanUtil.copyToList(dto, ApprovalSpecialist.class);
            approvalSpecialistService.saveBatch(approvalSpecialists);
        }
        return R.ok();
    }


}
